package cn.mdmm.web.filter;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.mdmm.service.memcached.MemcachedService;
import cn.mdmm.service.weixin.WxAccountInfoService;
import cn.modoumama.common.utils.ConfigProperty;
import cn.modoumama.common.utils.DateUtils;
import cn.modoumama.common.utils.StringUtils;

public class WxAuthUserFilter implements HandlerInterceptor {
	@Autowired
	MemcachedService memcachedService;
	@Autowired
	WxAccountInfoService wxAccountInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if (request.getSession().getAttribute("openId") != null) {
			return true;
		} else {
			return setSession(request, response);
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

	private boolean setSession(HttpServletRequest request, HttpServletResponse response) {
		StringBuffer host = request.getRequestURL();
		String qstr = request.getQueryString();
		String url = host.toString();
		if (qstr != null) {
			url = url + "?" + qstr;
		}

		if (Pattern.matches(".*modoumama\\.cn.*", host)) {
			String key = StringUtils.getUnique();
			memcachedService.set(key, url, DateUtils.TimeSecond.DAY);

			try {
				response.sendRedirect(
						wxAccountInfoService.getAutlUrl(ConfigProperty.getProperty("com.qq.weixin.accountNo"),
								ConfigProperty.getProperty("wx.auth.url"), key));
			} catch (IOException e) {
				e.printStackTrace();
			}

			return false;
		} else {
			String openId = "o-ot9xIj9DhC50IaMjDV7ssFN1u4";
			String headImgUrl = "http://k2.jsqq.net/uploads/allimg/1706/7_170629152344_5.jpg";
			request.getSession().setAttribute("openId", openId);
			request.getSession().setAttribute("logo", headImgUrl);
			return true;
		}
	}
}
